package top.pcat;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import lombok.extern.slf4j.Slf4j;
import top.pcat.entity.ANSI;
import top.pcat.entity.Message;
import top.pcat.service.Client;
import top.pcat.util.ProtostuffUtils;

import java.util.Scanner;

import static java.lang.Thread.sleep;
import static top.pcat.entity.ANSI.ANSI_RESET;

@Slf4j
public class ClientMain {

    private static final String GREEN = "\033[1;32m"; // 头部信息
    private static final String CYAN = "\033[1;36m"; // 普通信息
    private static final String YELLOW = "\033[1;33m"; // 警告信息
    private static final String RED = "\033[1;31m"; // 错误信息

    private static int port = 9999;

    public static String host;

    private static String ip;

    private static String gatewayhost ="127.0.0.1:6633";

    public static void main(String[] args) throws Exception {

        System.out.println(ANSI.ANSI_GREEN+"╔══════════════════════════════════════════════════════════════════");
        System.out.println("║            > 欢迎来到聊天室！                     ");
        System.out.println("║            > 正在为你连接"+ANSI.ANSI_YELLOW+" 127.0.0.1:6633 "+ANSI.ANSI_GREEN+"网关服务器！          ");
        log.info("连接网关服务器");

        do {
            byte[] result2 = HttpRequest.post("http://localhost:6633/")
                    .header(Header.USER_AGENT, "Hutool http")//头信息，多个头信息多次调用此方法即可
                    .timeout(20000)//超时，毫秒
                    .execute().bodyBytes();
            //Console.log(result2);
            host= ProtostuffUtils.deserialize(result2, String.class);


            if (!host.equals("无服务器可用")){
                break;
            }else{
                System.out.println("║            > 无服务器可用！正在重试！                 ");
                log.info("无服务器可用");
            }
            Thread.sleep(1500);
        }while (true);

        log.info("连接服务器："+host);

        String[] split = host.split(":");
        ip = split[0];
        port = Integer.parseInt(split[1]);

        Scanner scanner = new Scanner(System.in);
        System.out.print("║            > "+ANSI.ANSI_GREEN +"请输入你的名字: ");
        String name = scanner.next();
        log.info(ANSI_RESET + "你好，"+name+" !");

        String senderId = Message.newSenderId();

        Client client = new Client(senderId,name,ip,port);
        client.client();


    }
}